package org.lex.keytool.core.runner;

import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;

import org.lex.keytool.core.task.Task;
import org.lex.keytool.util.StringUtils;
import org.lex.keytool.util.process.ProcessLauncuer;

public class ForkTaskRunner extends AbstractTaskRunner {
	public static final String KEYTOOL = "keytool";
	private final Writer out;
	private final Writer err;

	public ForkTaskRunner(Writer out, Writer err) {
		this.out = out;
		this.err = err;
	}

	@Override
	public Future<Integer> run(Task task) throws Exception {
		List<String> cmds = this.createCommands(task);
		log.info("args: " + StringUtils.argsToString(cmds.toArray(new String[0])));
		return new ProcessLauncuer().launch(out, err, cmds);
	}

	private List<String> createCommands(Task task) {
		String[] args = task.buildArguments();
		List<String> cmds = new ArrayList<String>(1 + args.length);
		cmds.add(KEYTOOL);
		Collections.addAll(cmds, args);
		return cmds;
	}
}
